import React, { useState,useEffect } from 'react'
import { CheckOutlined } from '@ant-design/icons'
import './index.less'

export default function Sort (props) {
  const {
    sortFields = [],
    sortTypes = [],
    sortChange = ()=>{}
  } = props
  const [selectField, setSortField] = useState('createTime')
  const [selectType, setSortType] = useState('desc')
  const [isMounted,setIsMounted] = useState(false)

  // 在初始化时不调用sortChange，在selectField或selectType更新的时候再调用
  useEffect(()=>{
    if (isMounted){
      sortChange(`${selectField} ${selectType}`)
    } else {
      setIsMounted(true)
    }
  },[selectField,selectType])

  const sortClick = (data, type) => {
    if (type === 'field') {
      setSortField(data.value)
    } else {
      setSortType(data.value)
    }
  }
  return (
    <>
      <div className='sort-box' style={{ borderBottom: '1px solid #fafafa' }}>
        {
          sortFields.map((item, index) => {
            return (
              <div className='selection-box' key={index} onClick={() => sortClick(item, 'field')}>
                <div className='selected-flag'>{selectField === item.value ? <CheckOutlined /> : ''}</div>
                <div className='selection-name'>{item.name}</div>
              </div>
            )
          })
        }
      </div>
      <div className='sort-box'>
        {
          sortTypes.map((item, index) => {
            return (
              <div className='selection-box' key={index} onClick={() => sortClick(item, 'type')}>
                <div className='selected-flag'>{selectType === item.value ? <CheckOutlined /> : ''}</div>
                <div className='selection-name'>{item.name}</div>
              </div>
            )
          })
        }
      </div>
    </>
  )
}
